package learn.qr;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author 宋贤坤
 * @date 2019/7/8 20:45
 */
public class MicroWeChatQr {

    public static void main(String[] args) {
        createQrPic();
    }

    private static String FILE_PATH = "D:\\tincerefood.jpg";
    private static final String appId = "wx8a4575c2cbfdb4b2";
    private static final String secretKey = "55cc115fa4a90751de198403ffad19c2";

    private static String la() {
        String get = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secretKey;
        String httpGet = HttpUtil.get(get);
        JSONObject jsonObject = JSONUtil.parseObj(httpGet);
        String access_token = (String) jsonObject.get("access_token");
        return access_token;
    }

    public static void createQrPic() {
        try {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + la());
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            JSONObject paramJson = new JSONObject();
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);
            paramJson.put("scene", "a=1234567890");
            paramJson.put("path", "pages/index/index");
            printWriter.write(paramJson.toString());
            printWriter.flush();
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(FILE_PATH));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

